<template>
  <div class="diagnosis-container">
    <!-- 页面标题和操作 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">诊断记录</h1>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>诊疗工作</el-breadcrumb-item>
          <el-breadcrumb-item>诊断记录</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreateDiagnosis">
          <el-icon><Plus /></el-icon>
          新建诊断
        </el-button>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-filter">
      <el-card shadow="never">
        <div class="filter-row">
          <el-input
            v-model="searchParams.patientName"
            placeholder="患者姓名"
            clearable
            style="width: 200px; margin-right: 16px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <el-select
            v-model="searchParams.diagnosisStatus"
            placeholder="诊断状态"
            clearable
            style="width: 150px; margin-right: 16px"
          >
            <el-option label="进行中" value="in_progress" />
            <el-option label="已完成" value="completed" />
          </el-select>

          <el-date-picker
            v-model="searchParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 300px; margin-right: 16px"
          />

          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 诊断记录列表 -->
    <div class="diagnosis-list">
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <span>诊断记录列表</span>
            <div class="card-actions">
              <el-tooltip content="刷新数据">
                <el-button text @click="refreshData">
                  <el-icon><Refresh /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </div>
        </template>

        <el-table
          :data="diagnosisList"
          v-loading="loading"
          style="width: 100%"
          @row-click="handleRowClick"
        >
          <el-table-column prop="record_no" label="诊断记录编号" width="150" />
          <el-table-column prop="patient_name" label="患者姓名" width="120">
            <template #default="{ row }">
              <div class="patient-info">
                <span class="patient-name">{{ row.patient_name }}</span>
                <span class="patient-age" v-if="row.age"
                  >({{ row.age }}岁)</span
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="gender" label="性别" width="80">
            <template #default="{ row }">
              <el-tag
                :type="row.gender === '男' ? 'primary' : 'danger'"
                size="small"
              >
                {{ row.gender }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="chief_complaint"
            label="主诉"
            min-width="200"
            show-overflow-tooltip
          />
          <el-table-column
            prop="preliminary_diagnosis"
            label="初步诊断"
            min-width="180"
            show-overflow-tooltip
          />
          <el-table-column prop="diagnosis_status" label="状态" width="120">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.diagnosis_status)" size="small">
                {{ getStatusText(row.diagnosis_status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="visit_time" label="诊断时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.visit_time) }}
            </template>
          </el-table-column>
          <el-table-column prop="doctor_name" label="接诊医生" width="120" />
          <el-table-column prop="department_name" label="就诊科室" width="150" />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button
                link
                type="primary"
                @click.stop="handleViewDetail(row)"
              >
                查看
              </el-button>
              <el-button
                link
                type="primary"
                @click.stop="handleContinueDiagnosis(row)"
                :disabled="row.diagnosis_status === 'completed'"
              >
                继续
              </el-button>
              <el-dropdown @command="(command) => handleCommand(command, row)">
                <el-button link type="primary">
                  更多
                  <el-icon><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="edit">编辑</el-dropdown-item>
                    <el-dropdown-item
                      command="createPrescription"
                      :disabled="row.diagnosis_status !== 'completed'"
                    >
                      开具处方
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="createExamination"
                      :disabled="row.diagnosis_status === 'completed'"
                    >
                      开具检查
                    </el-dropdown-item>
                    <el-dropdown-item command="print" divided
                      >打印</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 新建/编辑诊断对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="isEditing ? '编辑诊断记录' : '新建诊断记录'"
      width="90%"
      top="5vh"
    >
      <DiagnosisEdit
        v-if="editDialogVisible"
        :record-id="currentRecord?.diagnosis_id"
        :is-edit="isEditing"
        :patient-info="currentRecord"  
        @close="editDialogVisible = false"
        @saved="handleDiagnosisSaved"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useStore } from "vuex";
import { Search, Refresh, Plus, ArrowDown } from "@element-plus/icons-vue";
import DiagnosisEdit from "@/components/doctor/DiagnosisEdit.vue";
// 引入后端API服务
import { getDiagnosisRecordPagerDataByDoctorSearch } from "@/api/doctor";

// 响应式数据
const loading = ref(false);
const diagnosisList = ref([]);
const editDialogVisible = ref(false);
const isEditing = ref(false);
const currentRecord = ref(null);
const store = useStore();

// 搜索参数
const searchParams = reactive({
  patientName: "",
  diagnosisStatus: "",
  dateRange: "",
});

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 状态映射 - 根据新表结构调整
const statusMap = {
  in_progress: { text: "进行中", type: "primary" },
  completed: { text: "已完成", type: "success" },
};

// 计算属性
const filteredDiagnosisList = computed(() => {
  let list = diagnosisList.value;

  if (searchParams.patientName) {
    list = list.filter((item) =>
      item.patient_name.includes(searchParams.patientName)
    );
  }

  if (searchParams.diagnosisStatus) {
    list = list.filter(
      (item) => item.diagnosis_status === searchParams.diagnosisStatus
    );
  }

  return list;
});

// 方法
const getStatusText = (status) => {
  return statusMap[status]?.text || status;
};

const getStatusType = (status) => {
  return statusMap[status]?.type || "info";
};

const formatDateTime = (dateTime) => {
  // 简化处理，实际项目中可以使用dayjs等库
  if (!dateTime) return "-";
  return dateTime.replace("T", " ").substring(0, 16);
};

// 计算患者年龄（根据出生日期）
const calculateAge = (birthDate) => {
  if (!birthDate) return null;
  const today = new Date();
  const birth = new Date(birthDate);
  let age = today.getFullYear() - birth.getFullYear();
  const monthDiff = today.getMonth() - birth.getMonth();
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
    age--;
  }
  return age;
};

// 加载数据
const loadDiagnosisData = async () => {
  loading.value = true;
  try {
    // TODO: 替换为真实接口调用
    const response = await getDiagnosisRecordPagerDataByDoctorSearch({
      doctor_id: store.state.user?.user_id, // 假设当前医生ID为123
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize,
      patient_name: searchParams.patientName,
      diagnosis_status: searchParams.diagnosisStatus,
      startDate: searchParams.dateRange?.[0],
      endDate: searchParams.dateRange?.[1]
    })

    console.log("诊断记录数据:", response);

    if(response && response.code == 200){
      diagnosisList.value = response.data.data;
      pagination.total = response.data.total;
      pagination.pagetotal = response.data.pagetotal;
    }
  } catch (error) {
    console.error("加载诊断记录失败:", error);
    ElMessage.error("加载诊断记录失败");
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1;
  loadDiagnosisData();
};

const handleReset = () => {
  Object.assign(searchParams, {
    patientName: "",
    diagnosisStatus: "",
    dateRange: "",
  });
  pagination.currentPage = 1;
  loadDiagnosisData();
};

// 分页处理
const handleSizeChange = (newSize) => {
  pagination.pageSize = newSize;
  pagination.currentPage = 1;
  loadDiagnosisData();
};

const handleCurrentChange = (newPage) => {
  pagination.currentPage = newPage;
  loadDiagnosisData();
};

// 刷新数据
const refreshData = async () => {
  await loadDiagnosisData();
  ElMessage.success("数据已刷新");
};

// 行点击事件
const handleRowClick = (row) => {
  
  handleViewDetail(row);
};

// 查看详情改为直接编辑
const handleViewDetail = (record) => {
  currentRecord.value = record;
  isEditing.value = true;
  editDialogVisible.value = true;
};

// 继续诊断
const handleContinueDiagnosis = (record) => {
  currentRecord.value = record;
  isEditing.value = true;
  editDialogVisible.value = true;
};

// 新建诊断
const handleCreateDiagnosis = () => {
  currentRecord.value = null;
  isEditing.value = false;
  editDialogVisible.value = true;
};

// 更多操作
const handleCommand = async (command, record) => {
  switch (command) {
    case "edit":
      currentRecord.value = record;
      isEditing.value = true;
      editDialogVisible.value = true;
      break;
    case "createPrescription":
      // TODO: 跳转到处方管理页面
      ElMessage.info("跳转到处方管理");
      break;
    case "createExamination":
      // TODO: 跳转到检查开具页面
      ElMessage.info("跳转到检查开具");
      break;
    case "print":
      handlePrint(record);
      break;
  }
};

// 打印处理
const handlePrint = (record) => {
  ElMessage.success(`开始打印诊断记录: ${record.record_no}`);
  // TODO: 实现打印功能
};

// 诊断保存后的处理
const handleDiagnosisSaved = (resData,shouldClose) => {
  editDialogVisible.value = shouldClose ? false : true;
  refreshData();
};

// 生命周期
onMounted( async() => {
  await loadDiagnosisData();
  ElMessage.success("诊断记录加载完成");
});
</script>

<style lang="scss" scoped>
.diagnosis-container {
  padding: 16px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
  
  // 平板优化
  @media (min-width: 768px) and (max-width: 1199px) {
    padding: 20px;
  }
  
  // PC大屏优化
  @media (min-width: 1200px) {
    padding: 24px;
  }
}

.page-header {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 20px;
  
  // 平板及以上设备横向布局
  @media (min-width: 768px) {
    flex-direction: row;
    justify-content: space-between;
    align-items: flex-start;
    gap: 20px;
  }

  .header-left {
    .page-title {
      margin: 0 0 8px 0;
      font-size: 20px;
      color: #303133;
      
      @media (min-width: 768px) {
        font-size: 24px;
      }
    }
    
    .el-breadcrumb {
      font-size: 12px;
      
      @media (min-width: 768px) {
        font-size: 14px;
      }
    }
  }

  .header-actions {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
    
    // 移动端按钮全宽
    @media (max-width: 767px) {
      width: 100%;
      
      .el-button {
        flex: 1;
        min-width: 0;
      }
    }
    
    @media (min-width: 768px) {
      flex-wrap: nowrap;
    }
  }
}

.search-filter {
  margin-bottom: 20px;

  .filter-row {
    display: flex;
    flex-direction: column;
    gap: 12px;
    
    // 平板及以上设备横向布局
    @media (min-width: 768px) {
      flex-direction: row;
      align-items: center;
      flex-wrap: wrap;
    }

    .el-input,
    .el-select,
    .el-date-picker {
      width: 100%;
      
      @media (min-width: 768px) {
        width: auto;
        flex: 0 0 auto;
      }
    }
    
    .el-input {
      @media (min-width: 768px) {
        width: 180px;
      }
      
      @media (min-width: 992px) {
        width: 200px;
      }
    }
    
    .el-select {
      @media (min-width: 768px) {
        width: 140px;
      }
      
      @media (min-width: 992px) {
        width: 150px;
      }
    }
    
    .el-date-picker {
      @media (min-width: 768px) {
        width: 260px;
      }
      
      @media (min-width: 992px) {
        width: 300px;
      }
    }
    
    .el-button {
      width: 100%;
      
      @media (min-width: 768px) {
        width: auto;
        flex: 0 0 auto;
      }
    }
  }
}

.diagnosis-list {
  .card-header {
    display: flex;
    flex-direction: column;
    gap: 12px;
    
    @media (min-width: 576px) {
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      gap: 16px;
    }
  }

  .patient-info {
    display: flex;
    align-items: center;
    gap: 4px;

    .patient-name {
      font-weight: 500;
    }

    .patient-age {
      color: #909399;
      font-size: 12px;
    }
  }
  
  // 表格响应式处理
  :deep(.el-table) {
    .el-table__header-wrapper,
    .el-table__body-wrapper {
      overflow-x: auto;
    }
    
    // 移动端表格单元格内边距调整
    @media (max-width: 767px) {
      .el-table__cell {
        padding: 8px 4px;
      }
    }
  }
  
  // 操作列在移动端调整
  :deep(.el-table) {
    @media (max-width: 767px) {
      .el-table__row {
        .el-table__cell:last-child {
          position: sticky;
          right: 0;
          background: white;
          box-shadow: -2px 0 4px rgba(0, 0, 0, 0.1);
        }
      }
    }
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 16px 0;
  
  // 平板及以上设备右对齐
  @media (min-width: 768px) {
    justify-content: flex-end;
  }
  
  // 移动端分页简化
  @media (max-width: 767px) {
    :deep(.el-pagination) {
      .btn-prev,
      .btn-next,
      .el-pager li {
        margin: 0 2px;
        min-width: 32px;
      }
      
      .el-pagination__jump {
        display: none;
      }
    }
  }
}

// 表格行悬停效果
:deep(.el-table__row) {
  cursor: pointer;

  &:hover {
    background-color: #f5f7fa;
  }
  
  // 移动端悬停效果优化
  @media (max-width: 767px) {
    &:active {
      background-color: #ebf0f5;
    }
  }
}

// 对话框样式优化 - 响应式
:deep(.el-dialog) {
  border-radius: 8px;
  margin: 20px auto;
  
  @media (max-width: 767px) {
    width: calc(100% - 40px) !important;
    margin: 20px auto;
    max-height: calc(100vh - 40px);
  }
  
  @media (min-width: 768px) and (max-width: 1199px) {
    width: 85% !important;
  }
  
  @media (min-width: 1200px) {
    width: 90% !important;
  }

  .el-dialog__header {
    border-bottom: 1px solid #ebeef5;
    margin-right: 0;
    padding: 16px 20px;
    
    @media (max-width: 767px) {
      padding: 12px 16px;
    }
  }
  
  .el-dialog__body {
    padding: 20px;
    max-height: calc(90vh - 120px);
    overflow-y: auto;
    
    @media (max-width: 767px) {
      padding: 16px;
      max-height: calc(100vh - 100px);
    }
  }
}

// 操作按钮组响应式
.operation-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  
  @media (max-width: 767px) {
    .el-button {
      flex: 1;
      min-width: 0;
      font-size: 12px;
      padding: 8px 12px;
    }
  }
}

// 下拉菜单在移动端优化
:deep(.el-dropdown) {
  @media (max-width: 767px) {
    .el-dropdown-link {
      padding: 8px 12px;
      font-size: 12px;
    }
  }
}

// 卡片阴影优化
:deep(.el-card) {
  @media (max-width: 767px) {
    border-radius: 8px;
    
    .el-card__header {
      padding: 12px 16px;
    }
    
    .el-card__body {
      padding: 16px;
    }
  }
  
  @media (min-width: 768px) {
    border-radius: 12px;
    
    .el-card__header {
      padding: 16px 20px;
    }
    
    .el-card__body {
      padding: 20px;
    }
  }
}

// 标签响应式
:deep(.el-tag) {
  @media (max-width: 767px) {
    font-size: 11px;
    padding: 4px 8px;
    height: auto;
    line-height: 1.2;
  }
}

</style>